package com.runfast.pay.wxpay;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

@Component("wxpayMiniConfigImpl")
public class WXPayMiniConfigImpl extends WXPayConfig {
    private final static Logger log = LoggerFactory.getLogger(WXPayMiniConfigImpl.class);
    private byte[] certData;
    @Value("${pay.account.mini.key}")
    private String key;
    @Value("${pay.account.mini.appId}")
    private String appId;
    @Value("${pay.account.mini.MchId}")
    private String mchId;

    private WXPayMiniConfigImpl() throws Exception {

        /*Resource resource = new DefaultResourceLoader().getResource("cert/apiclient_cert_public.p12");

        File file = resource.getFile();
        System.out.println(file.getAbsolutePath());
        InputStream certStream = resource.getInputStream();

        this.certData = new byte[(int) file.length()];
        certStream.read(certData);
        certStream.close();*/

        InputStream certStream = ClassUtils.class.getClassLoader().getResourceAsStream("cert/apiclient_cert_mini.p12");
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        while ((len = certStream.read(buffer)) > 0) {
            byteBuffer.write(buffer, 0, len);
        }
        certData = byteBuffer.toByteArray();


    }

    public String getAppID() {
        return this.appId;
    }

    public String getMchID() {
        return this.mchId;

    }

    public String getKey() {
        return this.key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public InputStream getCertStream() {
        log.info("###΢��֧��##### md5(֤��): " + DigestUtils.md5Hex(certData));
        ByteArrayInputStream certBis;
        certBis = new ByteArrayInputStream(this.certData.clone());
        return certBis;
    }


    public int getHttpConnectTimeoutMs() {
        return 2000;
    }

    public int getHttpReadTimeoutMs() {
        return 10000;
    }

    IWXPayDomain getWXPayDomain() {
        return WXPayDomainSimpleImpl.instance();
    }

    public String getPrimaryDomain() {
        return "api.mch.weixin.qq.com";
    }

    public String getAlternateDomain() {
        return "api2.mch.weixin.qq.com";
    }

    @Override
    public int getReportWorkerNum() {
        return 1;
    }

    @Override
    public int getReportBatchSize() {
        return 2;
    }

}
